from datetime import date

from django.db.models import Q
from django.shortcuts import render
from dateutil.parser import parse
from django.views import View
from django import http
from .models import Area, House, HouseImage
import json
from iHome.utils.upload_pictures import upload_pictures
from django.conf import settings
import datetime
from django.core.paginator import Paginator
from iHome.utils.views import LoginJsonRequiredMixin
from apps.orders.models import Order


# Create your views here.
class HouseDetailView(View):
    # 房屋详情
    def get(self, request, house_id):
        if request.user.is_authenticated:
            user_id = request.user.id
        else:
            user_id = -1
        try:
            house_model = House.objects.get(id=house_id)
        except:
            return http.JsonResponse({'errno': 4001, 'errmsg': '房源不存在'})
        comments = []
        orders = house_model.order_set.filter(status=4)
        for order in orders:
            comments.append({
                "comment": order.comment,
                "ctime": order.create_time.strftime('%Y-%m-%d'),
                "user_name": order.user.username
            })
        facilities = []
        for i in house_model.facility.all():
            facilities.append(i.id)
        img_urls = [
            str(house_model.index_image_url)
        ]
        house_image = HouseImage.objects.filter(house=house_model)
        for i in house_image:
            img_urls.append(i.url)
        house = {
            "acreage": house_model.acreage,
            "address": house_model.address,
            "beds": house_model.beds,
            "capacity": house_model.capacity,
            "comments": comments,
            "deposit": house_model.deposit,
            "facilities": facilities,
            "hid": house_id,
            "img_urls": img_urls,
            "max_days": house_model.max_days,
            "min_days": house_model.min_days,
            "price": house_model.price,
            "room_count": house_model.room_count,
            "title": house_model.title,
            "unit": house_model.unit,
            "user_avatar": str(house_model.user.avatar),
            "user_id": house_model.user.id,
            "user_name": house_model.user.username
        }
        data = {'user_id': user_id, 'house': house}
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})


class IndexHouseView(View):
    def get(self, request):
        houses = House.objects.all().order_by('-order_count')[:5]
        data = []
        for house in houses:
            data.append({
                "house_id": house.id,
                "img_url": str(house.index_image_url),
                "title": house.title
            })
        return http.JsonResponse({'errno': '0', 'errmsg': 'ok', 'data': data})


class MyHouseView(View):
    def get(self, request):
        # 我的房源
        user = request.user
        house_model_list = user.houses.all()
        houses = []
        for house_model in house_model_list:
            houses.append({
                "address": house_model.address,
                "area_name": house_model.area.name,
                "ctime": house_model.create_time.strftime('%Y-%m-%d'),
                "house_id": house_model.id,
                "img_url": str(house_model.index_image_url),
                "order_count": house_model.order_count,
                "price": house_model.price,
                "room_count": house_model.room_count,
                "title": house_model.title,
                "user_avatar": str(user.avatar)
            })
        data = {'houses': houses}
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})


class HouseImageView(View):
    # 上传房源图片
    def post(self, request, house_id):
        house_image = request.FILES.get('house_image').read()
        if not house_image:
            return http.JsonResponse({'errno': 4004, 'errmsg': '上传失败'})
        ret, info = upload_pictures(house_image)
        url = settings.AVATAR_URL + ret['key']

        try:
            house = House.objects.get(id=house_id, user=request.user)
            if house.index_image_url:
                HouseImage.objects.create(
                    house=house,
                    url=url
                )
            else:
                house.index_image_url = url
                house.save()
        except:
            return http.JsonResponse({'errno': 4004, 'errmsg': '上传失败'})
        data = {'url': url}
        return http.JsonResponse({'errno': 0, 'errmsg': '上传成功', 'data': data})


class AreaView(View):
    def get(self, request):
        # 获取城区列表
        areas = Area.objects.all()
        data = []
        for area in areas:
            data.append({
                'aid': area.id,
                'aname': area.name
            })
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})


class RentalsView(View):
    def get(self, request):
        # 搜索房源
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p')

        if sk == 'booking':
            sk = '-order_count'
        elif sk == 'price-inc':
            sk = 'price'
        elif sk == 'price-des':
            sk = '-price'
        elif sk == 'new':
            sk = '-update_time'
        if aid:
            add_id = Area.objects.get(id=aid)
            if sd and ed:
                sd = datetime.datetime.strptime(sd, '%Y-%m-%d')
                ed = datetime.datetime.strptime(ed, '%Y-%m-%d')
                day = (ed - sd).days
                order = Order.objects.filter(Q(begin_date__range=[sd, ed]) | Q(end_date__range=[sd, ed]))
                house_id = []
                for i in order:
                    if i.house.id not in house_id:
                        house_id.append(i.house.id)

                houses = House.objects.filter(Q(create_time__lt=sd) &
                                              Q(min_days__lte=day) & ~Q(id__in=house_id) & Q(area=add_id)).order_by(sk)

                # houses = House.objects.filter(create_time__lt=sd,
                #                               min_days__lte=day,
                #                               area=add_id, ).order_by(sk)
            else:
                houses = House.objects.filter(area=add_id).order_by(sk)
        else:
            if sd and ed:
                dayA = datetime.datetime.strptime(sd, '%Y-%m-%d')
                dayB = datetime.datetime.strptime(ed, '%Y-%m-%d')
                sub_day = dayB - dayA
                day = sub_day.days
                order = Order.objects.filter(Q(begin_date__range=[dayA, dayB]) | Q(end_date__range=[dayA, dayB]))
                house_id = []
                for i in order:
                    if i.house.id not in house_id:
                        house_id.append(i.house.id)
                print(house_id)
                houses = House.objects.filter(Q(create_time__lt=sd) &
                                              Q(min_days__lte=day) & ~Q(id__in=house_id)).order_by(sk)
            else:
                houses = House.objects.all().order_by(sk)

        house_list = []
        total_page = str(Paginator(houses, 10))
        data = {'houses': house_list, 'total_page': total_page}
        for i in houses:
            house_list.append({
                "address": i.address,
                "area_name": i.area.name,
                "ctime": i.create_time.strftime('%Y-%m-%d'),
                "house_id": i.id,
                "img_url": str(i.index_image_url),
                "order_count": i.order_count,
                "price": i.price,
                "room_count": i.room_count,
                "title": i.title,
                "user_avatar": str(i.user.avatar),
            })

        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})

    def post(self, request):
        # 发布房源
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        price = json_dict.get('price')
        area_id = json_dict.get('area_id')
        address = json_dict.get('address')
        room_count = json_dict.get('room_count')
        acreage = json_dict.get('acreage')
        unit = json_dict.get('unit')
        capacity = json_dict.get('capacity')
        beds = json_dict.get('beds')
        deposit = json_dict.get('deposit')
        min_days = json_dict.get('min_days')
        max_days = json_dict.get('max_days')
        facility = json_dict.get('facility')

        if not all([json_dict, title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit,
                    min_days, max_days, facility]):
            return http.JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})
        try:
            area = Area.objects.get(id=area_id)
        except:
            return http.JsonResponse({'errno': 4103, 'errmsg': '参数area_id错误'})
        house = House.objects.create(
            user=request.user,
            area=area,
            title=title,
            price=price,
            address=address,
            room_count=room_count,
            acreage=acreage,
            unit=unit,
            capacity=capacity,
            beds=beds,
            deposit=deposit,
            order_count=0,
            min_days=min_days,
            max_days=max_days,
        )
        house.facility.set(facility)

        data = {'house_id': house.id}
        return http.JsonResponse({'errno': 0, 'errmsg': '发布成功', 'data': data})
